package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.OrderMergeBean;
import com.hanson.common.bean.RefundParam;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.*;
import com.hanson.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Service
public class OrderRefundService {
    @Autowired
    private OrderRefundBeanMapper orderRefundBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private PayService payService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private ScoreSeqBeanMapper scoreSeqBeanMapper;
    @Autowired
    private AcctbkSeqBeanMapper acctbkSeqBeanMapper;
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SpreadMoneyBeanMapper spreadMoneyBeanMapper;

    /**
     * 申请退款
     *
     * @param orderSeq
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrderRefund(String orderSeq) {
        List<OrderBean> orderBeanList = orderService.selectByOrderId(orderSeq);
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            int orderStatus = 0;
            String openId = null;
            Integer payMoney = null;
            Integer score = null;
            Integer acctbkMoney = null;
            Set<Integer> metIdSet = new TreeSet<>();
            for (OrderBean orderBean : orderBeanList) {
                openId = orderBean.getOpenId();
                orderStatus = orderBean.getStatus();
                payMoney = orderBean.getPayPrice();
                score = orderBean.getUserScore();
                acctbkMoney = orderBean.getUserMoney();
                if (orderBean.getOrderType() == 1) {
                    GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
                    if (null != goodsBean) {
                        metIdSet.add(goodsBean.getMerId());
                    }
                } else if (orderBean.getOrderType() == 2 || orderBean.getOrderType() == 3) {
                    metIdSet.add(0);
                }
            }
            OrderRefundBean orderRefundBean = new OrderRefundBean();
            orderRefundBean.setCreateTime(new Date());
            orderRefundBean.setStatus(1);
            orderRefundBean.setOrderSeq(orderSeq);
            orderRefundBean.setOpenId(openId);
            orderRefundBean.setTotalMoney(payMoney);
            orderRefundBean.setOrderStatus(orderStatus);
            orderRefundBean.setScore(score);
            orderRefundBean.setAcctbkMoney(acctbkMoney);
            orderRefundBeanMapper.insert(orderRefundBean);
            orderService.updateStatus(7, orderSeq);
            payMoney = null == payMoney ? 0 : payMoney;
            //发送短信到掌柜提醒处理
            smsService.refundOrderNotify(metIdSet, orderSeq, payMoney);
        }
    }

    /**
     * 同意退款
     *
     * @param orderRefundBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void agreeRefund(OrderRefundBean orderRefundBean) {
        List<OrderRefundBean> orderRefundBeanList = orderRefundBeanMapper.selectByOrderSeq(orderRefundBean.getOrderSeq());
        if (CollectionUtils.isNotEmpty(orderRefundBeanList)) {
            OrderRefundBean returnBean = orderRefundBeanList.get(0);
            int refundMoney = BusinessUtil.getDbAmount(orderRefundBean.getWebRefundMoney());
            if (refundMoney > returnBean.getTotalMoney()) {
                throw new BusinessException("退款金额不能大于支付金额！");
            }
            if (refundMoney > 0) {
                RefundParam refundParam = new RefundParam();
                refundParam.setOrderSeq(returnBean.getOrderSeq());
                refundParam.setRefundFee(refundMoney);
                refundParam.setRefundDesc("申请退款");
                payService.refund(refundParam);
                returnBean.setRefundMoney(refundMoney);
            }

            UserBean userBean = userBeanMapper.selectByOpenId(returnBean.getOpenId());
            //收回送的积分和钱
            List<ScoreSeqBean> scoreSeqBeanList = scoreSeqBeanMapper.selectByOrderSeq(orderRefundBean.getOrderSeq());
            if (CollectionUtils.isNotEmpty(scoreSeqBeanList)) {
                for (ScoreSeqBean scoreSeqBean : scoreSeqBeanList) {
                    if (scoreSeqBean.getType() == 1) {
                        //送的积分收回
                        scoreSeqBean.setId(null);
                        scoreSeqBean.setRemark("退款回收赠送积分");
                        scoreSeqBean.setType(2);
                        scoreSeqBean.setCreateDate(new Date());
                        scoreSeqBeanMapper.insert(scoreSeqBean);
                        userBean.setScore(userBean.getScore() - scoreSeqBean.getScore());
                        userBean.setUpdateDate(new Date());
                    }
                }
            }
            List<SpreadMoneyBean> spreadMoneyBeanList = spreadMoneyBeanMapper.selectByOrderSeq(orderRefundBean.getOrderSeq());
            if (CollectionUtils.isNotEmpty(spreadMoneyBeanList)) {
                //收回佣金
                for (SpreadMoneyBean spreadMoneyBean : spreadMoneyBeanList) {
                    if (spreadMoneyBean.getIsAccount() == 0) {
                        //未到账的佣金 删除
                        spreadMoneyBeanMapper.deleteByPrimaryKey(spreadMoneyBean.getId());
                    } else if (spreadMoneyBean.getIsAccount() == 1) {
                        //已到账的佣金 回退
                        AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
                        acctbkSeqBean.setType(2);
                        acctbkSeqBean.setMoney(String.valueOf(spreadMoneyBean.getSpreadMoney()));
                        acctbkSeqBean.setRemark("退款回收佣金");
                        acctbkSeqBean.setCreateDate(new Date());
                        acctbkSeqBean.setOpenId(returnBean.getOpenId());
                        acctbkSeqBeanMapper.insert(acctbkSeqBean);
                        userBean.setMoney(userBean.getMoney() - spreadMoneyBean.getSpreadMoney());
                        userBean.setUpdateDate(new Date());
                        spreadMoneyBeanMapper.deleteByPrimaryKey(spreadMoneyBean.getId());
                    }
                }
            }

            int refundScore = null == returnBean.getScore() ? 0 : returnBean.getScore();
            int refundAcctbkMoney = null == returnBean.getAcctbkMoney() ? 0 : returnBean.getAcctbkMoney();
            if (refundScore > 0 || refundAcctbkMoney > 0) {
                if (refundScore > 0) {
                    //有积分可退
                    ScoreSeqBean scoreSeqBean = new ScoreSeqBean();
                    scoreSeqBean.setType(1);
                    scoreSeqBean.setScore(refundScore);
                    scoreSeqBean.setRemark("退款返还积分");
                    scoreSeqBean.setCreateDate(new Date());
                    scoreSeqBean.setOpenId(returnBean.getOpenId());
                    scoreSeqBean.setOrderSeq(orderRefundBean.getOrderSeq());
                    scoreSeqBeanMapper.insert(scoreSeqBean);
                    userBean.setScore(userBean.getScore() + refundScore);
                    userBean.setUpdateDate(new Date());
                }
                if (refundAcctbkMoney > 0) {
                    //有账户余额可退
                    AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
                    acctbkSeqBean.setType(1);
                    acctbkSeqBean.setMoney(String.valueOf(refundAcctbkMoney));
                    acctbkSeqBean.setRemark("退款返还余额");
                    acctbkSeqBean.setCreateDate(new Date());
                    acctbkSeqBean.setOpenId(returnBean.getOpenId());
                    acctbkSeqBeanMapper.insert(acctbkSeqBean);
                    userBean.setMoney(userBean.getMoney() + refundAcctbkMoney);
                    userBean.setUpdateDate(new Date());
                }
            }
            returnBean.setStatus(2);
            returnBean.setUpdateTime(new Date());
            orderRefundBeanMapper.updateByPrimaryKey(returnBean);
            orderService.updateStatus(8, orderRefundBean.getOrderSeq());

            userBeanMapper.updateByPrimaryKeySelective(userBean);
            redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
            OrderBean orderBean = orderService.selectUserInfo(orderRefundBean.getOrderSeq());
            if (null != orderBean) {
                smsService.refundResultNotify(orderBean.getUserName(), orderBean.getUserPhone(), "同意退款");
            }
        } else {
            throw new BusinessException("无退款申请！");
        }
    }

    /**
     * 不同意退款
     *
     * @param orderRefundBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void notAgreeRefund(OrderRefundBean orderRefundBean) {
        if (StringUtils.isEmpty(orderRefundBean.getReson())) {
            throw new BusinessException("拒绝退款原因不能为空！");
        }
        List<OrderRefundBean> orderRefundBeanList = orderRefundBeanMapper.selectByOrderSeq(orderRefundBean.getOrderSeq());
        if (CollectionUtils.isNotEmpty(orderRefundBeanList)) {
            OrderRefundBean returnBean = orderRefundBeanList.get(0);
            returnBean.setStatus(3);
            returnBean.setReson(orderRefundBean.getReson());
            returnBean.setUpdateTime(new Date());
            orderRefundBeanMapper.updateByPrimaryKey(returnBean);
            orderService.updateStatus(returnBean.getOrderStatus(), orderRefundBean.getOrderSeq());
            OrderBean orderBean = orderService.selectUserInfo(orderRefundBean.getOrderSeq());
            if (null != orderBean) {
                smsService.refundResultNotify(orderBean.getUserName(), orderBean.getUserPhone(), "拒绝退款");
            }
        }
    }

    /**
     * 退款记录详情
     *
     * @param orderSeq
     * @return
     */
    public OrderRefundBean detail(String orderSeq) {
        List<OrderRefundBean> orderRefundBeanList = orderRefundBeanMapper.selectByOrderSeq(orderSeq);
        if (CollectionUtils.isNotEmpty(orderRefundBeanList)) {
            OrderRefundBean orderRefundBean = orderRefundBeanList.get(0);
            orderRefundBean.setWebRefundMoney(BusinessUtil.getWebAmount(orderRefundBean.getTotalMoney()));
            return orderRefundBean;
        }
        return null;
    }

    /**
     * 用户退款记录
     *
     * @param page
     * @param openId
     * @return
     */
    public Page<OrderRefundBean> listOrderRefund(Page<OrderRefundBean> page, String openId) {
        OrderRefundBean orderRefundBean = new OrderRefundBean();
        orderRefundBean.setOpenId(openId);
        List<OrderRefundBean> orderRefundBeanList = orderRefundBeanMapper.listOrderRefund(page, orderRefundBean);
        List<OrderRefundBean> returnList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderRefundBeanList)) {
            for (OrderRefundBean refundBean : orderRefundBeanList) {
                List<OrderBean> orderBeanList = orderService.selectByOrderId(refundBean.getOrderSeq());
                List<OrderMergeBean> mergeBeanList = orderService.mergeOrders(orderBeanList, new ModelMap());
                if (CollectionUtils.isEmpty(mergeBeanList)) {
                    continue;
                } else {
                    refundBean.setWebRefundMoney(BusinessUtil.getWebAmount(refundBean.getRefundMoney()));
                    refundBean.setOrderMergeBean(mergeBeanList.get(0));
                    returnList.add(refundBean);
                }
            }
        }
        return page.setRecords(returnList);
    }
}
